package com.xiaoxing.zhinenghuacangku_nanjinglu.mvp.ui.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.dds.soap.SoapListener;
import com.dds.soap.SoapParams;
import com.dds.soap.SoapUtil;
import com.hss01248.photoouter.PhotoUtil;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.BaseConstants;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.LogUtils;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.xiaoxing.zhinenghuacangku_nanjinglu.R;
import com.xiaoxing.zhinenghuacangku_nanjinglu.R2;
import com.xiaoxing.zhinenghuacangku_nanjinglu.di.component.DaggerNanJingLu_JianXiuRuKuComponent;
import com.xiaoxing.zhinenghuacangku_nanjinglu.di.module.NanJingLu_JianXiuRuKuModule;
import com.xiaoxing.zhinenghuacangku_nanjinglu.mvp.contract.NanJingLu_JianXiuRuKuContract;
import com.xiaoxing.zhinenghuacangku_nanjinglu.mvp.model.entity.GetReturnGoodMeterTask;
import com.xiaoxing.zhinenghuacangku_nanjinglu.mvp.model.entity.GetUserSpaceListForAutoStore;
import com.xiaoxing.zhinenghuacangku_nanjinglu.mvp.presenter.JianXiuRuKuPresenter;
import com.xiaoxing.zhinenghuacangku_nanjinglu.mvp.ui.adapter.JianXiuRuKuAdapter;
import com.xiaoxing.zhinenghuacangku_nanjinglu.mvp.ui.entity.JianXiuRuKu;

import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import com.jess.arms.utils.CProgressDialogUtils;
import me.jessyan.armscomponent.commonres.utils.ToolbarUtils;
import me.jessyan.armscomponent.commonres.view.NiceSpinner;
import me.jessyan.armscomponent.commonsdk.core.RouterHub;
import pub.devrel.easypermissions.EasyPermissions;

import static android.support.v7.widget.DividerItemDecoration.VERTICAL;
import static com.jess.arms.utils.Preconditions.checkNotNull;


@Route(path = RouterHub.ZHI_NENG_HUA_CANG_KU_NANJINGLU_ACTIVITY_JIAN_XIU_RU_KU)
public class NanJingLu_JianXiuRuKuActivity extends BaseActivity<JianXiuRuKuPresenter> implements NanJingLu_JianXiuRuKuContract.View, OnRefreshListener, JianXiuRuKuAdapter.IJianXiuRuKuAdapter {

    @BindView(R2.id.empty_text)
    TextView empty_text;
    @BindView(R2.id.empty_image)
    ImageView empty_image;
    @BindView(R2.id.empty)
    View mEmptyLayout;
    @BindView(R2.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R2.id.refreshLayout)
    RefreshLayout mRefreshLayout;
    @BindView(R2.id.et_weizhi)
    EditText etWeizhi;
    @BindView(R2.id.nice_position_cang_wei)
    NiceSpinner spPosition; //仓位下拉选
    private JianXiuRuKuAdapter mJianXiuRuKuAdapter;
    private List<GetReturnGoodMeterTask> mGetReturnGoodMeterTask = new ArrayList<>();
    private String selectedKuWeiId = ""; //已选择的库位id，可以选择多个物料
    private int mSelectedSpid;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerNanJingLu_JianXiuRuKuComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .nanJingLu_JianXiuRuKuModule(new NanJingLu_JianXiuRuKuModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_jian_xiu_ru_ku; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        ToolbarUtils.initToolbarTitleBack(this, getString(R.string.activity_jian_xiu_ru_ku));
        initRefreshLayout();
        initRecyclerView();
        initEmpty();
//        cangWeiChaXun();
        getReturnGoodMeterTask();
    }

    private void initRefreshLayout() {
        mRefreshLayout.setRefreshHeader(new
                ClassicsHeader(this).setSpinnerStyle(SpinnerStyle.FixedBehind).setPrimaryColorId(R.color.public_colorPrimary).setAccentColorId(android.R.color.white));
        mRefreshLayout.setOnRefreshListener(this);
        mRefreshLayout.setEnableRefresh(false);
        mRefreshLayout.autoRefresh();
        mRefreshLayout.setEnableLoadMore(false);
    }

    private void initRecyclerView() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.addItemDecoration(new DividerItemDecoration(this, VERTICAL));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setAdapter(mJianXiuRuKuAdapter = new JianXiuRuKuAdapter(this, mGetReturnGoodMeterTask, this));
//        //优化嵌套卡顿
//        mRecyclerView.setHasFixedSize(true);
//        mRecyclerView.setNestedScrollingEnabled(false);
//        mRecyclerView.setItemViewCacheSize(600);
//        RecyclerView.RecycledViewPool recycledViewPool = new RecyclerView.RecycledViewPool();
//        mRecyclerView.setRecycledViewPool(recycledViewPool);
//        mAdapter.setChuKuInterface(this);
    }

    private void initEmpty() {
        empty_image.setImageResource(R.drawable.ic_empty);
        empty_text.setTextColor(Color.parseColor("#CFCFCF"));
        empty_text.setText("暂无数据");
    }

    /**
     * 获取检修完成待入库列表
     */
    public void getReturnGoodMeterTask() {
        showLoading();

        String methodNames = "GetReturnGoodMeterTask";
        SoapParams params = new SoapParams();
        SoapUtil.getInstance(this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodNames, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();
                try {
                    cangWeiChaXun();
                    String result = object.getProperty(methodNames + "Result").toString();
                    if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {

                        List<GetReturnGoodMeterTask> getReturnGoodMeterTasks = ArmsUtils.parseString2List(result, GetReturnGoodMeterTask.class);

                        if (getReturnGoodMeterTasks != null && getReturnGoodMeterTasks.size() > 0) {

                            mGetReturnGoodMeterTask.clear();
                            mGetReturnGoodMeterTask.addAll(getReturnGoodMeterTasks);
                            mJianXiuRuKuAdapter.notifyDataSetChanged();
                            mEmptyLayout.setVisibility(View.GONE);
                            mRecyclerView.setVisibility(View.VISIBLE);
                        }

                    } else {
                        mEmptyLayout.setVisibility(View.VISIBLE);
                        mRecyclerView.setVisibility(View.GONE);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();

            }
        }, getAapiUserName(), getApiPwd());
    }

    @Override
    public void showLoading() {
        CProgressDialogUtils.showProgressDialog(this);
    }

    @Override
    public void hideLoading() {
        CProgressDialogUtils.cancelProgressDialog();

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.makeText(this, message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @OnClick(R2.id.tv_check)
    public void cangWeiChaXun() {

        getUserSpaceListForAutoStore(mSharedPreferencesHelper.getString(BaseConstants.UID), getCangWei());

    }

    private void getUserSpaceListForAutoStore(String user_id, String spname) {
        showLoading();


        String methodName = "GetUserSpaceListForAutoStoreQingDao";
        SoapParams params = new SoapParams();
        params.put("user_id", user_id);
        params.put("spname", spname);
        params.put("ismeter", "1");

        /**
         * 请求
         */
        String finalMethodName = methodName;
        SoapUtil.getInstance(this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();
                try {

                    String result = object.getProperty(finalMethodName + "Result").toString();
                    if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {

                        List<GetUserSpaceListForAutoStore> getUserSpaceListForAutoStoreList = ArmsUtils.parseString2List(result, GetUserSpaceListForAutoStore.class);
                        initSpPosition(getUserSpaceListForAutoStoreList);

                    } else {
                        if (spPosition != null) {
                            spPosition.clearData();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());
    }

    private String getCangWei() {
        return etWeizhi.getText().toString().trim();
    }

    private void initSpPosition(List<GetUserSpaceListForAutoStore> getUserSpaceListForAutoStoreList) {
        ArrayList<String> spnames = new ArrayList<String>();
        ArrayList<String> mSpids = new ArrayList<String>();
        HashMap<String, GetUserSpaceListForAutoStore> getUserSpaceListForAutoStoreHashMap = new HashMap<>();

        for (int i = 0; i < getUserSpaceListForAutoStoreList.size(); i++) {
            spnames.add(String.valueOf(
                    new StringBuilder().append(getUserSpaceListForAutoStoreList.get(i).getSpname())
            ));
            if (getUserSpaceListForAutoStoreList.get(i).getSptname().equals("入库待检区")) {
                mSpids.add(String.valueOf(getUserSpaceListForAutoStoreList.get(i).getSpid()));
            }
            getUserSpaceListForAutoStoreHashMap.put(getUserSpaceListForAutoStoreList.get(i).getSpname(), getUserSpaceListForAutoStoreList.get(i));
        }
        spPosition.attachDataSource(spnames);
        GetUserSpaceListForAutoStore getUserSpaceListForAutoStore = getUserSpaceListForAutoStoreHashMap.get(spPosition.getFullWidthAdapter().getItem(0));
        mSelectedSpid = getUserSpaceListForAutoStore.getSpid();

        LogUtils.debugEInfo("spid==" + mSelectedSpid);


        spPosition.addOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                GetUserSpaceListForAutoStore getUserSpaceListForAutoStore = getUserSpaceListForAutoStoreHashMap.get(spPosition.getFullWidthAdapter().getItem(position));

                mSelectedSpid = getUserSpaceListForAutoStore.getSpid();

                LogUtils.debugEInfo("spid==" + mSelectedSpid);

            }
        });
    }

    @OnClick(R2.id.btn_commit_ruku)
    void queDingRuKu() {

//        returnGoodMeterCallliKuWithSALVERID(,selectedKuWeiId,);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 101) {
            Bundle extras = data.getExtras();
            if (extras != null) {
//                mScanSpid = extras.getString("scan_result");
            }

        } else if (resultCode == 102) {//扫描物料二维码(有二维码的质检样品)
            Bundle extras = data.getExtras();
//            mid = extras.getString("scan_result");

        } else {
            if (resultCode != 0)
                PhotoUtil.onActivityResult(this, requestCode, resultCode, data);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
        if (requestCode == 103) {
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        super.onKeyDown(keyCode, event);

        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {

            return true;
        }

        return super.onKeyDown(keyCode, event);


    }

    @Override
    public void getJianXiuRuKuDataSuccess(JianXiuRuKu entityData) {

    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {

    }

    @Override
    public void queDingRuKu(GetReturnGoodMeterTask item) {
        returnGoodMeterCallliKuWithSALVERID(item.getTaskid(), String.valueOf(mSelectedSpid), item.getMid());
    }

    /**
     * 确定入库
     */
    public void returnGoodMeterCallliKuWithSALVERID(String taskid, String spid, String mid) {
        showLoading();

        String methodNames = "ReturnGoodMeterCallliKuWithSALVERID";
        SoapParams params = new SoapParams();
        params.put("taskid", taskid);
        params.put("spid", spid);
        params.put("uid", mSharedPreferencesHelper.getString(BaseConstants.UID));
        params.put("SALVERID", "1");
        params.put("mid", mid);
        SoapUtil.getInstance(this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodNames, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();
                try {

                    String result = object.getProperty(methodNames + "Result").toString();
                    if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {

                        if (result.equals("true")) {
                            showMessage("命令执行成功");
                            getReturnGoodMeterTask();

                        } else {
                            showMessage("命令执行失败");
                        }

                    } else {

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();

            }
        }, getAapiUserName(), getApiPwd());
    }
}
